<template>
  <n-space class="comments" vertical>
    <n-space justify="space-between">
      <n-form
        ref="formRef"
        inline
        :model="formValue"
        label-placement="left"
        :rules="rules"
      >
        <n-form-item path="name">
          <n-input placeholder="请输入评论人" v-model:value="formValue.name" />
        </n-form-item>
        <n-form-item path="ip">
          <n-input placeholder="请输入ip" v-model:value="formValue.ip" />
        </n-form-item>
        <n-form-item path="status">
          <n-select
            v-model:value="formValue.status"
            placeholder="请选中状态"
            clearable
            :options="options"
          />
        </n-form-item>
        <n-form-item>
          <n-button @click="findClick"> 查询 </n-button>
        </n-form-item>
      </n-form>
    </n-space>
    <n-data-table
      :columns="columns"
      :data="data"
      :pagination="pagination"
      :bordered="false"
      remote
      :row-key="rowKey"
      @update:page-size="handlePageSizeChange"
      @update:page="handlePageChange"
    />
  </n-space>
</template>

<script setup lang="ts">
import {
  type FormInst,
  type FormItemRule,
  NTag,
  NForm,
  NFormItem,
  NInput,
  NButton,
  NSelect,
  NSpace,
  NDataTable,
  NPagination,
  type SelectOption,
  type SelectGroupOption,
  type DataTableColumns,
} from "naive-ui";
import {
  StatusComment,
  type Comment,
  findAll as apiFindListComments,
  deleteById as apiDeleteComments,
} from "~/api/comments";
useHead({
  title: "评论管理", //网站标题
});
definePageMeta({
  title: "评论管理",
});

const formRef = ref<FormInst | null>();
const formValue = ref<{
  name: string;
  ip: string;
  status: StatusComment | null;
}>({
  name: "",
  ip: "",
  status: null,
});
const rules = {
  name: {
    pattern: /^.{0,10}$/,
    message: "查询长度小于10",
    trigger: "input",
  },
  ip: {
    pattern: /^.{0,10}$/,
    message: "查询长度小于10",
    trigger: "input",
  },
};
const options: Array<SelectOption | SelectGroupOption> = [
  {
    label: "Pass",
    value: "pass",
  },
  {
    label: "Block",
    value: "block",
  },
  {
    label: "Review",
    value: "review",
  },
];

const findClick = (e: MouseEvent) => {
  e.preventDefault();
  const messageReactive = naiveui.message.loading("Verifying", {
    duration: 0,
  });
  formRef.value?.validate(async (errors) => {
    if (!errors) {
      getCommentList();
    } else {
      naiveui.message.error(errors[0][0].message ?? "表单验证错误");
    }
    messageReactive.destroy();
  });
};

const dayjs = useDayjs();
const createColumns = ({
  deleteComment,
}: {
  deleteComment: (row: Comment) => void;
}): DataTableColumns<Comment> => {
  return [
    {
      title: "评论人",
      key: "name",
    },
    {
      title: "评论内容",
      key: "content",
    },
    {
      title: "ua",
      key: "ua",
      render(row: Comment) {
        const browser = h(
          NTag,
          {
            type: "success",
          },
          {
            default: () => parseBrowser(row.ua),
          }
        );
        const os = h(
          NTag,
          {
            type: "info",
          },
          {
            default: () => parseOS(row.ua),
          }
        );
        return h(
          NSpace,
          {
            vertical: true,
          },
          {
            default: () => [browser, os],
          }
        );
      },
    },
    {
      title: "ip",
      key: "ip",
    },
    {
      title: "状态",
      key: "status",
      render(row: Comment) {
        return h(
          NTag,
          {
            type:
              row.status === StatusComment.Pass
                ? "success"
                : row.status === StatusComment.Review
                ? "info"
                : "error",
          },
          {
            default: () => row.status,
          }
        );
      },
    },
    {
      title: "创建时间",
      key: "createTime",
      render(row: Comment) {
        return dayjs(row.createTime).format("YYYY年MM月DD日");
      },
    },
    {
      title: "",
      key: "actions",
      render(row: Comment) {
        return h(
          NButton,
          {
            strong: true,
            tertiary: true,
            size: "small",
            onClick: () => deleteComment(row),
          },
          { default: () => "删除" }
        );
      },
    },
  ];
};

const data = ref<Comment[]>([]);

const columns = createColumns({
  async deleteComment(row: Comment) {
    await apiDeleteComments(row.id);
    // getCommentList();
  },
});
const rowKey = (rowData: { id: any }) => {
  return rowData.id;
};
const handlePageChange = (page: number) => {
  pagination.value.page = page;
  getCommentList();
};
const handlePageSizeChange = (pageSize: number) => {
  pagination.value.pageSize = pageSize;
  pagination.value.page = 1;
  getCommentList();
};
const pagination = ref({
  page: 1,
  pageSize: 10,
  itemCount: 0,
  pageSizes: [3, 5, 7],
});

const getCommentList = async () => {
  const res = await apiFindListComments({
    ...formValue.value,
    pageNum: pagination.value.page,
    pageSize: pagination.value.pageSize,
  });
  if (res.data) {
    pagination.value.itemCount = res.data.count;
    data.value = res.data.list;
  }
};
onMounted(async () => {
  getCommentList();
});
</script>
<style lang="scss" scoped>
.comments {
  padding: 20px 15px;
  .n-input,
  .n-select {
    width: 200px;
  }
  .n-pagination {
    justify-content: center;
  }
}
</style>
